package com.songshuai.sales.client.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.songshuai.sales.client.dto.request.frontsop.*;
import com.songshuai.sales.client.dto.response.frontsop.ArticleSopResDto;
import com.songshuai.sales.client.dto.response.frontsop.ListResDto;
import com.songshuai.sales.client.service.FrontSopService;
import com.songshuai.webapi.baseapi.constant.miniprogram.CacheKeys;
import com.songshuai.webapi.baseapi.dto.pangu.request.salesclient.CustomerListReqDto;
import com.songshuai.webapi.baseapi.enumerations.ResultStatus;
import com.songshuai.webapi.baseapi.enumerations.sales.redis.RedisExpire;
import com.songshuai.webapi.baseapi.pojo.BaseParmDto;
import com.songshuai.webapi.baseapi.pojo.QueryPageRes;
import com.songshuai.webapi.baseapi.pojo.QueryResponse;
import com.songshuai.webapi.baseapi.utils.OssUploadUtil;
import com.songshuai.webapi.baseapi.utils.PageUtil;
import com.songshuai.webapi.baseapi.utils.SnowFlakeUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
import java.util.List;
import java.util.concurrent.CompletableFuture;

@Slf4j
@Api("小程序端SOP接口")
@RestController
@RequestMapping("/api/front/sop/")
public class FrontSopController extends BaseController {

    @Autowired
    private SnowFlakeUtil snowFlakeUtil;
    @Autowired
    private OssUploadUtil uploadUtil;


//    @Value("${file.basePath}")
//    private String fileBasePath;

    @Autowired
    private FrontSopService frontSopService;


    /**
     * sop列表
     */
    @ApiOperation(value = "销售助手-sop列表")
    @RequestMapping(value = "showList", method = RequestMethod.POST)
    public CompletableFuture<QueryResponse<List<ListResDto>>> showList( @RequestBody BaseParmDto<ListReqDto> request){

        String currentUserId = this.getCurrentUserId();
        //String currentUserId = "1";
        return CompletableFuture.supplyAsync(()->{


            if(null == currentUserId){
                return new QueryResponse(ResultStatus.FAIL.getErrorCode(),ResultStatus.FAIL.getErrorMsg());
            }

            try{

                request.getParam().setCurrentUserId(currentUserId);
                PageUtil page = null;

                //是否有缓存
                PageUtil cache = this.getSyncSopRedis(request);
                if(cache != null){
                    page = cache;
                }else{
                    page = frontSopService.showList(request);
                    //设置缓存
                    this.setSyncSopRedis(request, page);
                }

                List<ListResDto> listRecordResDtos = (List<ListResDto>)page.getLists();
                return QueryPageRes.setQueryResponseData(listRecordResDtos,page.getTotalSize()==null?0L:page.getTotalSize().longValue());

            } catch (Exception e) {
                log.error("api/front/sop/showList", e);
                return new QueryResponse(ResultStatus.FAILOfficial.getErrorCode(),e.getMessage());
            }
        });
    }
    //提取销售端sop列表缓存
    public PageUtil getSyncSopRedis(BaseParmDto<ListReqDto> request){

        int pageIndex = request.getPageIndex();
        int pageSize = request.getPageSize();
        String title = request.getParam().getTitle();
        String subType = request.getParam().getSubType();
        String labelId = request.getParam().getLabelId();



        subType = StringUtils.isBlank(subType) == true? "0": subType;
        labelId = StringUtils.isBlank(labelId) == true? "0": labelId;
        String redisKey = pageIndex + "_" + pageSize + "_" + subType + "_" + labelId;
        try {
            if (title == null) {
                Object obj = redisUtil.hget(CacheKeys.SALE_SOP_INFO, redisKey);
                PageUtil p = JSON.parseObject((String)obj,PageUtil.class);
                log.info("get cache:{}",redisKey);
                return p;
            }
        }catch (Exception e){
            log.error("api/front/sop/showList", e);
            return null;
        }
        return null;
    }

    //销售端sop列表缓存
    @Async
    public void setSyncSopRedis(BaseParmDto<ListReqDto> request, PageUtil page){

        int pageIndex = request.getPageIndex();
        int pageSize = request.getPageSize();
        String title = request.getParam().getTitle();
        String subType = request.getParam().getSubType();
        String labelId = request.getParam().getLabelId();

        subType = StringUtils.isBlank(subType) == true? "0": subType;
        labelId = StringUtils.isBlank(labelId) == true? "0": labelId;
        try {
            if (title == null) {
                String redisKey = pageIndex + "_" + pageSize + "_" + subType + "_" + labelId;
                JSONObject o = (JSONObject) JSON.toJSON(page);
                redisUtil.hset(CacheKeys.SALE_SOP_INFO, redisKey, o.toJSONString(), RedisExpire.TenMinutes.getCode());
                log.info("set cache:{}",redisKey);
            }
        }catch (Exception e){
            log.error("api/front/sop/showList", e);
        }



    }



    /**
     * sop详情
     */
    @ApiOperation(value = "sop详情")
    @RequestMapping(value = "articleSop", method = RequestMethod.POST)
    public CompletableFuture<QueryResponse> articleSop(@RequestBody ArticleSopReqDto request){

        String currentUserId = this.getCurrentUserId();

        return CompletableFuture.supplyAsync(()-> {

            if(null == currentUserId){
                return new QueryResponse(ResultStatus.FAIL.getErrorCode(),ResultStatus.FAIL.getErrorMsg());
            }

            try {
                request.setCurrentUserId(currentUserId);
                ArticleSopResDto articleSopResDto = frontSopService.articleSop(request);
                return QueryResponse.setResData(articleSopResDto);
            } catch (Exception e) {
                log.error("api/front/sop/articleSop", e);
                return new QueryResponse(ResultStatus.FAILOfficial.getErrorCode(),e.getMessage());
            }

        });

    }


    /**
     * 我的推送客户列表(需要盘古接口-未提供)
     */
    @ApiOperation(value = "推送客户列表")
    @RequestMapping(value = "customerList", method = RequestMethod.POST)
    public CompletableFuture<QueryResponse> customerList(@RequestBody BaseParmDto<CustomerListReqDto> request){

        String currentUserId = this.getCurrentUserId();
        //String currentUserId = "1";
        return CompletableFuture.supplyAsync(()-> {

            if(null == currentUserId){
                return new QueryResponse(ResultStatus.FAIL.getErrorCode(),ResultStatus.FAIL.getErrorMsg());
            }

            try {
                request.getParam().setCurrentUserId(currentUserId);
                return frontSopService.customerList(request);

            } catch (Exception e) {
                log.error("api/front/sop/customerList", e);
                return new QueryResponse(ResultStatus.FAILOfficial.getErrorCode(),e.getMessage());
            }
        });

    }


    /**
     * 销售推送SOP给客户接口
     */
    @ApiOperation(value = "推送接口")
    @RequestMapping(value = "sendSop", method = RequestMethod.POST)
    public CompletableFuture<QueryResponse> send(@RequestBody SendReqDto request){

        String currentUserId = this.getCurrentUserId();
        //String currentUserId = "1";
        return CompletableFuture.supplyAsync(()-> {

            if(null == currentUserId){
                return new QueryResponse(ResultStatus.FAIL.getErrorCode(),ResultStatus.FAIL.getErrorMsg());
            }

            try {
                request.setCurrentUserId(currentUserId);
                Map map =  frontSopService.sendSop(request);
                return QueryResponse.setResData(map);
            } catch (Exception e) {
                log.error("api/front/sop/sendSop", e);
                return new QueryResponse(ResultStatus.FAILOfficial.getErrorCode(),e.getMessage());
            }

        });
    }











    
    /**
     * sop点赞
     */
    @ApiOperation(value = "sop点赞")
    @RequestMapping(value = "goodSop", method = RequestMethod.POST)
    public CompletableFuture<QueryResponse> goodSop(@RequestBody GoodReqDto request){

        String currentUserId = this.getCurrentUserId();
        return CompletableFuture.supplyAsync(()-> {

            if(null == currentUserId){
                return new QueryResponse(ResultStatus.FAIL.getErrorCode(),ResultStatus.FAIL.getErrorMsg());
            }

            try {
                request.setCurrentUserId(currentUserId);
                frontSopService.goodSop(request);
                return QueryResponse.setResData(null);
            } catch (Exception e) {
                log.error("api/front/sop/goodSop", e);
                return new QueryResponse(ResultStatus.FAILOfficial.getErrorCode(),e.getMessage());
            }

        });

    }


    /**
     * 关闭sop浏览
     */
    @ApiOperation(value = "关闭浏览")
    @RequestMapping(value = "closeView", method = RequestMethod.POST)
    public CompletableFuture<QueryResponse> closeView(@RequestBody CloseViewReqDto request){

        String currentUserId = this.getCurrentUserId();
        return CompletableFuture.supplyAsync(()-> {

            if(null == currentUserId){
                return new QueryResponse(ResultStatus.FAIL.getErrorCode(),ResultStatus.FAIL.getErrorMsg());
            }

            try {
                request.setCurrentUserId(currentUserId);
                frontSopService.closeView(request);
                return QueryResponse.setResData(null);
            } catch (Exception e) {
                log.error("api/front/sop/closeView", e);
                return new QueryResponse(ResultStatus.FAILOfficial.getErrorCode(),e.getMessage());
            }

        });

    }




}
